<template>
  <ElContainer class="bg-white created-activity">
    <el-main>
      <headerstepsVue
        v-bind="{ successstatus, submit, list: _list }"
      ></headerstepsVue>
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="rule"
        size="default"
        label-width="120px"
        class="demo-ruleForm"
      >
        <el-tabs v-model="active" class="tabs" tab-position="left">
          <el-tab-pane lazy label="比赛信息配置" name="比赛信息配置">
            <el-row>
              <el-col :span="6">
                <el-form-item label="比赛名" prop="name">
                  <div class="el-input">
                    <el-input v-model="ruleForm.name"></el-input>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="默认语言">
                  <el-select v-model="ruleForm.language" placeholder="请选择">
                    <el-option label="C" value="C">C</el-option>
                    <el-option label="C++" value="C++">C++</el-option>
                    <el-option label="Python" value="Python">Python</el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6"
                ><el-form-item label="默认开启O2">
                  <el-select v-model="ruleForm.iso2" placeholder="请选择">
                    <el-option label="关闭" :value="false"></el-option>
                    <el-option label="开启" :value="true"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6"
                ><el-form-item label="文件读写">
                  <el-select v-model="ruleForm.isfile" placeholder="请选择">
                    <el-option label="关闭" :value="false"></el-option>
                    <el-option label="开启" :value="true"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="比赛时间" prop="signupstarttime">
              <el-date-picker
                v-model="startTime"
                :unlink-panels="true"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY/MM/DD HH:mm"
              ></el-date-picker>
            </el-form-item>
            <!-- <el-form-item label="比赛赛制">
							<el-radio v-model="ruleForm.format" value="OI">OI</el-radio>
							<small class="text-black-50">OI：无实时排名，只能提交一次，交卷后统一评测</small>
							<br>
							<el-radio v-model="ruleForm.format" value="IOI">IOI</el-radio>
							<small class="text-black-50">IOI：有实时排名，每道题可以提交多次</small>
						</el-form-item> -->
            <el-form-item label="比赛模式">
              <el-radio v-model="duration" :value="false"
                >全员统一计时</el-radio
              >
              <small class="text-black-50"
                >该模式为所有人在比赛时间内进行答题，一般使用该模式</small
              >
              <br />
              <el-radio v-model="duration" :value="true">个人单独计时</el-radio>
              <small class="text-black-50"
                >所有人在比赛期间任意时间进入答题，受答题时长有限制。例如比赛持续全天，限制2小时，学生A可以从9点进入，11点交卷；学生B可以从14点进入，16点交卷</small
              >
            </el-form-item>
            <el-form-item label="类别标签">
              <el-select-v2
                class=""
                size="default"
                v-model="ruleForm.label"
                :options="matchLabels"
                clearable
                filterable
                multiple
                collapse-tags
                collapse-tags-tooltip
                :max-collapse-tags="3"
                placeholder="请输入,可输入名称查询"
              >
              </el-select-v2>
            </el-form-item>
            <el-form-item label="客服配置" v-if="isAdmin && !tenant_id">
              <el-select
                v-model="ruleForm.customerserviceid"
                placeholder="请选择"
                clearable
              >
                <el-option
                  v-for="v in customerservice"
                  :label="v.name"
                  :value="Number(v.ID)"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="下发文件">
              <el-upload
                ref="upload"
                class="upload-demo"
                action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
                accept=".zip,.rar"
                :http-request="request"
                :limit="1"
                @remove="(e) => (ruleForm.file = '')"
                :file-list="
                  ruleForm.file
                    ? [{ url: ruleForm.file, name: ruleForm.file }]
                    : []
                "
                :on-exceed="handleExceed"
              >
                <template #trigger>
                  <el-button type="primary">+ 上传文件</el-button>
                </template>
                <!-- <template #tip> -->
                <div>
                  <small class="text-black-50"
                    >注1：下发文件将在比赛开始时展示在比赛封面。只支持单个zip或rar格式文件。</small
                  >
                </div>
                <div>
                  <small class="text-black-50"
                    >注2：文件地址为您的文件上传编码后的实际地址。</small
                  >
                </div>
                <!-- </template> -->
                <!-- <small class="text-black-50" v-if="ruleForm.file">文件地址：{{ ruleForm.file }}</small> -->
              </el-upload>
            </el-form-item>
            <el-form-item v-show="duration" label="答题时间">
              <el-input-number
                :step="5"
                :min="0"
                :max="1200"
                step-strictly
                v-model="ruleForm.duration"
              >
              </el-input-number
              >&nbsp;分钟
            </el-form-item>
            <el-form-item v-if="isAdmin" label="比赛积分">
              <el-input-number
                :step="1"
                :min="1"
                :max="100"
                step-strictly
                v-model="ruleForm.integral"
              ></el-input-number>
            </el-form-item>
            <el-form-item label="比赛说明" prop="context">
              <Wangeditor
                id="context"
                :value="context"
                ref="contexteditor"
                :zIndex="2"
                :context="htmlcontext"
              >
              </Wangeditor>
            </el-form-item>
            <el-form-item
              label="比赛说明可见权限"
              label-width="150px"
              v-if="ruleForm.type === 'public'"
            >
              <el-radio-group v-model="ruleForm.isinvitation">
                <el-radio :value="true">所有参赛人员可见</el-radio>
                <el-radio :value="false">所有人可见</el-radio>
              </el-radio-group>
              <br />
              <small class="text-black-50"
                >这里参赛人员指：<br />
                1）若这个比赛是公开比赛（公开比赛需要报名），则参赛人员为报名人员；<br />
                2）若这个比赛是私有比赛（私有比赛不需要报名），则参赛人员为比赛人员列表的人；<br />
                3）系统超级管理员除外。</small
              >
            </el-form-item>
            <div class="row">
              <div class="col" :class="!ruleForm.ID ? 'text-center' : ''">
                <el-button
                  @click="submit(_list[1].title)"
                  :style="{
                    '--el-button-bg-color': '#434343',
                    '--el-button-border-color': '#434343',
                  }"
                  size="large"
                  type="primary"
                  >下一步，{{ _list[1].title }}</el-button
                >
              </div>
              <div v-show="ruleForm.ID" class="col text-right">
                <el-button type="info" size="large" @click="close"
                  >取消</el-button
                >
                <el-button @click="() => submit()" type="primary" size="large"
                  >保存</el-button
                >
              </div>
            </div>
          </el-tab-pane>

          <el-tab-pane lazy label="用户配置" name="用户配置">
            <el-form-item label="比赛类型" prop="type">
              <el-radio-group v-model="matchType">
                <el-radio value="public">公开比赛</el-radio>
                <el-radio value="team">单个团队专属比赛</el-radio>
                <el-radio value="limit">非公开比赛</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item
              v-if="MatchType.PUBLIC === matchType"
              label="配置激活码"
            >
              <el-tooltip
                class="box-item"
                effect="dark"
                content="如填写此选项，参赛者需要通过输入比赛激活码验证，如果多个激活码请用英文逗号分开"
                placement="top"
              >
                <el-input
                  placeholder="可以设置比赛激活码，对于需要报名的比赛，需要激活码才可以报名"
                  :step="1"
                  :min="4"
                  :max="4"
                  step-strictly
                  v-model="ruleForm.invitation"
                ></el-input>
              </el-tooltip>
            </el-form-item>
            <el-form-item label="激活码客服" v-if="isAdmin && !tenant_id">
              <el-select
                v-model="ruleForm.info!.customerservice"
                placeholder="请选择"
                clearable
              >
                <el-option
                  v-for="v in customerservice"
                  :label="v.name"
                  :value="v.qrcode!"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item v-if="MatchType.TEAM === matchType" label="配置团队">
              <el-select
                v-model="ruleForm.teamid"
                placeholder="请选择搜索团队或ID"
                filterable
                :remote-method="remoteMethod1"
                :loading="loading"
                remote
                clearable
                reserve-keyword
              >
                <el-option
                  v-for="item in getteam"
                  :key="item.ID"
                  :label="item.name"
                  :value="Number(item.ID)"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-row
              v-if="MatchType.LIMIT === matchType"
              :gutter="10"
              style="margin-bottom: 18px"
            >
              <el-col :span="12">
                <el-form-item label="批量从团队添加">
                  <el-row :gutter="10" justify="space-between">
                    <el-col :span="16">
                      <el-select
                        v-model="_teamid"
                        placeholder="请选择搜索团队或ID"
                        filterable
                        :remote-method="remoteMethod1"
                        :loading="loading"
                        remote
                        clearable
                        reserve-keyword
                      >
                        <el-option
                          v-for="item in getteam"
                          :key="item.ID"
                          :label="item.name"
                          :value="Number(item.ID)"
                        ></el-option>
                      </el-select>
                    </el-col>
                    <el-col :span="8">
                      <el-button @click="changeteamid(_teamid)" type="primary">
                        加入参赛名单
                      </el-button>
                    </el-col>
                  </el-row>
                </el-form-item>
                <el-form-item label="搜索单用户添加">
                  <el-row :gutter="10" justify="space-between">
                    <el-col :span="16">
                      <el-select
                        placeholder="请输入名称或者手机号"
                        v-model="_userid"
                        filterable
                        :remote-method="remoteMethod2"
                        :loading="loading"
                        remote
                        clearable
                        reserve-keyword
                      >
                        <el-option
                          v-for="item in getuser"
                          :key="item.ID"
                          :label="item.name"
                          :value="Number(item.ID)"
                        ></el-option>
                      </el-select>
                    </el-col>
                    <el-col :span="8">
                      <el-button @click="_adduser(_userid)" type="primary">
                        加入参赛名单
                      </el-button>
                    </el-col>
                  </el-row>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-table
                  :data="users"
                  border
                  height="64vh"
                  style="width: 100%"
                >
                  <el-table-column prop="name" label="名称" width="" />
                  <el-table-column prop="phonenum" label="手机" width="" />
                  <el-table-column prop="gid" label="学籍号" width="" />
                  <el-table-column prop="address" label="删除" width="">
                    <template #default="scope">
                      <el-button
                        link
                        type="primary"
                        @click="users.splice(scope.$index, 1)"
                        size="small"
                        >删除</el-button
                      >
                    </template>
                  </el-table-column>
                </el-table>
              </el-col>
            </el-row>
            <div class="row m-mt-6">
              <div class="col">
                <el-button
                  @click="submit('比赛选项')"
                  :style="{
                    '--el-button-bg-color': '#434343',
                    '--el-button-border-color': '#434343',
                  }"
                  size="large"
                  type="primary"
                  >下一步，比赛选项</el-button
                >
              </div>
              <div class="col text-right">
                <el-button type="info" size="large" @click="close"
                  >取消</el-button
                >
                <el-button @click="() => submit()" type="primary" size="large"
                  >保存</el-button
                >
              </div>
            </div>
          </el-tab-pane>

          <el-tab-pane lazy label="题目配置" name="题目配置">
            <div>注： 如需导入非编程题，请通过题单导入题目。或者联系管理员</div>
            <selectquestionVue
              :isAdmin="isAdmin"
              v-model="questions"
              :teamid="teamid"
              :removeclick="removeclick"
              :addclick="addclick"
              :questionid="questions"
              index="oldid"
              :change="change"
            ></selectquestionVue>
            <div class="row m-mt-6">
              <div class="col">
                <el-button
                  @click="submit('分数配置')"
                  :style="{
                    '--el-button-bg-color': '#434343',
                    '--el-button-border-color': '#434343',
                  }"
                  size="large"
                  type="primary"
                  >下一步，分数配置</el-button
                >
              </div>
              <div class="col text-right">
                <el-button type="info" size="large" @click="close"
                  >取消</el-button
                >
                <el-button @click="() => submit()" type="primary" size="large"
                  >保存</el-button
                >
              </div>
            </div>
          </el-tab-pane>

          <el-tab-pane lazy label="分数配置" name="分数配置">
            <div :style="{ background: 'var(--color-f5)', padding: '24px' }">
              <div
                class="container-fluid bg-white"
                :style="{ padding: '24px' }"
              >
                <div class="row m-mb-6">
                  <div class="col">已添加题目</div>
                  <div class="col text-right">
                    <span>
                      已添加:
                      <span class="text-danger">{{ questions.length }}</span
                      >题
                    </span>
                  </div>
                </div>
                <div class="row">
                  <div
                    :style="{
                      width: '80px',
                      height: '42px',
                      lineHeight: '42px',
                    }"
                  >
                    编号
                  </div>
                  <div
                    class="col"
                    :style="{ height: '42px', lineHeight: '42px' }"
                  >
                    名称
                  </div>
                  <div
                    :style="{
                      width: '90px',
                      padding: 0,
                      height: '42px',
                      lineHeight: '42px',
                    }"
                  >
                    题目类型
                  </div>
                  <div
                    :style="{
                      width: '180px',
                      padding: 0,
                      height: '42px',
                      lineHeight: '42px',
                    }"
                    class="text-center"
                  >
                    设置分值
                  </div>
                  <div
                    :style="{
                      width: '190px',
                      padding: 0,
                      height: '42px',
                      lineHeight: '42px',
                    }"
                  >
                    测试点得分设置
                  </div>
                </div>
                <hr :style="{ marginTop: '6px', marginBottom: '6px' }" />
                <div class="mydata">
                  <div
                    class="row list"
                    v-for="v in questions"
                    :key="v.oldid"
                    :style="{ marginTop: '6px', marginBottom: '6px' }"
                  >
                    <div
                      :style="{
                        width: '80px',
                        height: '42px',
                        lineHeight: '42px',
                      }"
                    >
                      {{ v.oldid }}
                    </div>
                    <div
                      class="col text-truncate"
                      :style="{ height: '42px', lineHeight: '42px' }"
                    >
                      {{ v.name }}
                    </div>

                    <div
                      :style="{
                        width: '90px',
                        padding: 0,
                        height: '42px',
                        lineHeight: '42px',
                      }"
                    >
                      <button
                        class="text-center"
                        type="button"
                        :style="{
                          border: 0,
                          background: 'var(--color-f5)',
                          color: 'var(--color-43)',
                          width: '78px',
                          height: '30px',
                          lineHeight: '30px',
                          fontSize: '14px',
                          cursor: 'default',
                        }"
                      >
                        <svg class="icon icon-class-var" iner="true">
                          <use :xlink:href="iconname[v.type || '代码']" />
                        </svg>
                        {{ v.type }}
                      </button>
                    </div>
                    <div
                      class="text-center"
                      :style="{
                        width: '180px',
                        padding: 0,
                        height: '42px',
                        lineHeight: '42px',
                      }"
                    >
                      <el-input-number
                        :max="100"
                        :min="0"
                        v-model="v.score"
                      ></el-input-number>
                    </div>
                    <div
                      :style="{
                        width: '190px',
                        padding: 0,
                        height: '42px',
                        lineHeight: '42px',
                      }"
                    >
                      <el-button
                        v-show="v.type === '代码'"
                        @click="dialogVisibleindex = v.oldid || 0"
                        >测试点得分设置</el-button
                      >
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div class="row m-mt-6">
              <div class="col"></div>
              <div class="col text-right">
                <el-button type="info" size="large" @click="close"
                  >取消</el-button
                >
                <el-button @click="() => submit()" type="primary" size="large"
                  >保存</el-button
                >
              </div>
            </div>
          </el-tab-pane>

          <el-tab-pane lazy label="比赛选项" name="比赛选项">
            <el-text size="large" tag="b" v-if="isAdmin">赛前</el-text>
            <!-- 老OJ 使用 -->
            <div class="margin-top10" style="margin-top: 5px">
              <el-form-item v-if="isAdmin" label="比赛列表展示">
                <el-checkbox
                  v-if="!tenant_id"
                  type="checkbox"
                  v-model="isshow"
                  label="未登录系统用户可见"
                >
                </el-checkbox>
                <el-checkbox
                  type="checkbox"
                  v-model="usershow"
                  label="未报名该比赛人员可见"
                >
                </el-checkbox>
              </el-form-item>
            </div>
            <el-divider class="divider" v-if="isAdmin" />
            <el-text size="large" tag="b">赛中</el-text>
            <div class="margin-top10" style="margin-top: 5px">
              <el-form-item label="赛中得分和排名">
                <el-radio-group v-model="ruleForm.isrank" class="flex-column">
                  <el-radio :value="false"
                    >比赛中，学生页不展示实时排名</el-radio
                  >
                  <el-radio :value="true"
                    >比赛中，学生页要展示实时排名（可能有延时，不作为最终成绩依据）</el-radio
                  >
                </el-radio-group>
              </el-form-item>
              <el-form-item label="多次提交">
                <el-radio-group v-model="ruleForm.format" class="flex-column">
                  <el-radio value="OI">只能提交一次题目</el-radio>
                  <el-radio value="IOI"
                    >可以提交多次，各题目成绩以最后一次提交为准</el-radio
                  >
                </el-radio-group>
              </el-form-item>
              <el-form-item
                label="提交后展示内容"
                v-if="ruleForm.format === 'IOI'"
              >
                <el-radio-group
                  v-model="ruleForm.show_ac_status"
                  class="flex-column"
                >
                  <el-radio :value="SHOW_AC_STATUS.HIDE_AC_SCORE">
                    提交时【不展示该题结果】
                  </el-radio>
                  <el-radio :value="SHOW_AC_STATUS.SHOW_FULL_AC">
                    提交时【展示该题是否通过】（已通过：全AC；未通过：非全AC）
                  </el-radio>
                  <el-radio :value="SHOW_AC_STATUS.SHOW_SCORE">
                    提交时【展示该题得分】，不展示各个测试点得分情况
                  </el-radio>
                  <el-radio :value="SHOW_AC_STATUS.SHOW_DETAILED_SCORE">
                    提交时【展示该题得分】，并且展示各个【测试点得分情况】
                  </el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="题目名保护">
                <el-radio-group
                  v-model="ruleForm.isshowquestionname"
                  class="flex-column"
                >
                  <el-radio :value="false"
                    >比赛中隐藏题目名，用 "第*题" 代替</el-radio
                  >
                  <el-radio :value="true">比赛中不隐藏题目名</el-radio>
                </el-radio-group>
              </el-form-item>
            </div>
            <el-divider class="divider" />
            <el-text size="large" tag="b">赛后</el-text>
            <div class="margin-top10" style="margin-top: 5px">
              <el-form-item label="试卷结果展示">
                <el-radio-group v-model="ruleForm.result" class="flex-column">
                  <el-radio :value="0"
                    >交卷后，学生交卷界面立即展示最终得分（需要等待计算）</el-radio
                  >
                  <el-radio :value="3"
                    >交卷后，学生交卷界面不立即展示最终得分</el-radio
                  >
                </el-radio-group>
              </el-form-item>
              <el-form-item label="赛后排行榜">
                <el-radio-group
                  v-model="ruleForm.isranking"
                  class="flex-column"
                >
                  <el-radio :value="true">比赛结束后，展示赛后排行榜</el-radio>
                  <el-radio :value="false"
                    >比赛结束后，不展示赛后排行榜</el-radio
                  >
                </el-radio-group>
              </el-form-item>
              <el-form-item label="赛后查看代码" v-if="ruleForm.isranking">
                <el-radio-group
                  v-model="ruleForm.iswatchcode"
                  class="flex-column"
                >
                  <el-radio :value="true">可互相查看代码</el-radio>
                  <el-radio :value="false">只能看自己代码</el-radio>
                </el-radio-group>
              </el-form-item>
              <!-- 老OJ 使用 -->
              <el-form-item label="题单展示">
                <el-radio-group
                  v-model="ruleForm.isshowactivityquestionbank"
                  class=""
                >
                  <el-radio :value="false">比赛结束后展示题单</el-radio>
                  <el-radio :value="true">比赛结束后不展示题单</el-radio>
                </el-radio-group>
              </el-form-item>
              <!-- <el-form-item label="比赛代码查重">
								<el-radio v-model="ruleForm.isduplicate" :value="false">展示比赛查重数据</el-radio>
								<el-radio v-model="ruleForm.isduplicate" :value="true">不展示比赛查重数据</el-radio>
							</el-form-item> -->
            </div>
            <!-- <el-form-item v-if="isAdmin && !tenant_id" label="比赛讨论">
							<el-radio v-model="ruleForm.isapplication" :label="false">比赛过程中展示讨论板</el-radio>
							<el-radio v-model="ruleForm.isapplication" :label="true">比赛过程中隐藏讨论板</el-radio>
						</el-form-item> -->
            <!-- <el-form-item v-if="isAdmin" label="比赛列表展示">
							<el-checkbox v-if="!tenant_id" type="checkbox" v-model="isshow" label="未登录系统用户可见">
							</el-checkbox>
							<el-checkbox type="checkbox" v-model="usershow" label="未报名该比赛人员可见"> </el-checkbox>
						</el-form-item> -->
            <!-- <el-form-item label="试卷排行榜">
							<el-radio v-model="ruleForm.isranking" :label="true">展示排行榜</el-radio>
							<el-radio v-model="ruleForm.isranking" :label="false">不展示排行榜</el-radio>
						</el-form-item> -->
            <!-- <el-form-item label="题目保护">
							<el-form-item label-width="auto" label="是否隐藏题目名">
								<el-radio v-model="ruleForm.isshowquestionname" :label="false">是</el-radio>
								<el-radio v-model="ruleForm.isshowquestionname" :label="true">否</el-radio>
							</el-form-item>
							<el-form-item label-width="auto" label="比赛期间屏蔽系统同名题目">
								<el-radio v-model="istrue" :label="true">是</el-radio>
							</el-form-item>
						</el-form-item> -->
            <!-- <el-form-item label="题单展示">
							<el-radio v-model="ruleForm.isshowactivityquestionbank" :label="false">比赛结束后展示题单</el-radio>
							<el-radio v-model="ruleForm.isshowactivityquestionbank" :label="true">比赛结束后不展示题单</el-radio>
						</el-form-item>
						<el-form-item label="试卷结果展示">
							<el-radio v-model="ruleForm.result" :label="0">交卷展示得分</el-radio>
							<el-radio v-model="ruleForm.result" :label="3">不展示结果</el-radio>
						</el-form-item> -->
            <div class="row m-mt-6">
              <div class="col">
                <el-button
                  @click="submit('题目配置')"
                  :style="{
                    '--el-button-bg-color': '#434343',
                    '--el-button-border-color': '#434343',
                  }"
                  size="large"
                  type="primary"
                  >下一步，题目配置</el-button
                >
              </div>
              <div class="col text-right">
                <el-button type="info" size="large" @click="close"
                  >取消</el-button
                >
                <el-button
                  @click="() => submit()"
                  :loading="loading"
                  type="primary"
                  size="large"
                  >保存</el-button
                >
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <el-dialog v-model="dialogVisible2" title="测试点配置" width="1100px">
        <template #header>
          <span class="icon-text el-dialog__header-title">
            <el-icon class="text-primary">
              <Guide />
            </el-icon>
            测试点配置
          </span>
        </template>
        <TestcaseVue
          v-model:rule-form="matchquestionindex"
          v-bind="{
            download,
            addexample,
            getname,
            request: request2,
            downloadtip,
            settestcasesscore,
          }"
        ></TestcaseVue>
      </el-dialog>
    </el-main>
  </ElContainer>
</template>

<script setup lang="ts">
import {
  ElForm,
  ElMessage,
  ElNotification,
  UploadInstance,
  UploadProps,
  UploadRawFile,
  UploadRequestHandler,
  dayjs,
  genFileId,
} from "element-plus";
import JSZip from "jszip";
import { debounce } from "lodash-es";
import { assign } from "underscore";
import { computed, inject, onMounted, reactive, ref, watch } from "vue";
import { RouteLocationRaw, useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";
import { Activity, SHOW_AC_STATUS } from "../../admin/views/data";
import { activityrules } from "../../admin/views/data/formrules";
import {
  Iobj,
  asyncgetactivity,
  asyncgetcustomerservice,
  asyncselectactivityuser,
  asyncselectmatchquestion,
  asyncselectteamuser,
} from "../../api";
import { EMstatus, Storekey } from "../../interface";
import Studycodemodel from "../../mysql_interface/studycodemodel";
import { findpid } from "../../util/code";
import updateoss, { downloadexamplezip, updatezip } from "../../util/updateoss";
import TestcaseVue from "../createdquestion/testcase.vue";
import selectquestionVue from "../selectquestion/index.vue";
import Wangeditor from "../wangeditor.vue";
import headerstepsVue from "./headersteps.vue";
import { LabelType } from "@/util/data";

const tenant_id = inject<string | undefined>("tenant_id", undefined);

const istrue = ref(true);
const _teamid = ref<number>();
const _userid = ref<number>();

const iconname = {
  代码: "#icon-icon_tianjiatimu_code",
  单选: "#icon-icon_tianjiatimu_single",
  多选: "#icon-icon_tianjiatimu_multiple",
  判断: "#icon-icon_tianjiatimu_panduan",
  填空: "#icon-icon_tianjiatimu_edit",
  排序: "#icon-icon_tianjiatimu_edit",
  拍照: "#icon-icon_tianjiatimu_edit",
};

const users = ref<Studycodemodel.Iuser[]>([]);

const list = [
  {
    title: "比赛信息配置",
    description: "配置比赛的基础信息",
  },
  {
    title: "用户配置",
    description: "参赛用户配置",
    isAdmin: true,
  },
  {
    title: "比赛选项",
    description: "更多比赛配置",
  },
  {
    title: "题目配置",
    description: "配置比赛题目内容",
  },

  {
    title: "分数配置",
    description: "配置比赛分数",
  },
];
const _list = computed(() => {
  return list.filter((c) => !c.isAdmin || c.isAdmin === p.isAdmin);
});

const getteam = computed(() => {
  return store.state.team?.rows;
});
const getuser = computed(() => {
  return store.state.users?.rows;
});
// label
const getlabel = computed(() => {
  return store.state.label?.rows || [];
});
const matchLabels = computed(() => {
  // e.tenant_id == tenant_id 数据库中没有值是null 要用==
  return findpid(
    getlabel.value.filter((e) => {
      return (
        e.type === LabelType.MATCH &&
        (tenant_id ? e.tenant_id == tenant_id : true)
      );
    })
  ).map((e) => ({ label: e.name, value: e.ID }));
});

const duration = ref(false);
const dialogVisibleindex = ref(0);
const dialogVisible2 = ref(false);
const loading = ref(false);

const matchquestionindex = computed<Studycodemodel.Iquestion>({
  set(e) {
    const n = questions.value.findIndex(
      (e) => e.oldid === dialogVisibleindex.value
    );
    if (n !== -1 && e) {
      const t: Studycodemodel.Imatchquestion = e;
      t.example = e.testcases;
      questions.value.splice(n, 0, e);
    }
  },
  get() {
    const data =
      questions.value.find((e) => e.oldid === dialogVisibleindex.value) || {};
    const n: Studycodemodel.Iquestion = data;
    n.testcases = data.example;
    return n;
  },
});

async function download() {
  console.log(123456456);
  const example = matchquestionindex.value?.testcases;
  if (example && example.length) {
    ElMessage.info("打包中，请稍后……");
    await downloadexamplezip(example, matchquestionindex.value.name);
    ElMessage.info("下载完成");
  } else {
    ElMessage.info("没有测试点");
  }
}

/**
 * 添加测试
 */
function addexample(i: boolean, index?: number) {
  const question = questions.value.find(
    (e) => e.oldid === dialogVisibleindex.value
  );
  if (!question) return;

  if (i) {
    if (!question.example) {
      question.example = [];
    }
    if (question.example.length < 50) {
      const newTestCase = {
        input: "",
        output: "",
        isshow: true,
        score: undefined,
        type: "data" as const,
      };
      if (index !== undefined) {
        question.example.splice(index + 1, 0, newTestCase);
      } else {
        question.example.push(newTestCase);
      }
    }
  } else {
    if (question.example) {
      if (index !== undefined) {
        question.example.splice(index, 1);
      } else {
        question.example.pop();
      }
    }
  }
}

function getname(url: string) {
  const t = url.split("/");
  return t[t.length - 1];
}

const router = useRouter();
const route = useRoute();

const p = defineProps<{
  teamid?: number;
  ID?: number;
  isAdmin: boolean;
  createdorupdateactivtiy: (data: {
    data: Studycodemodel.Iactivity;
    question: Studycodemodel.Imatchquestion[];
    users: Studycodemodel.Iuser[];
    teamid?: number;
  }) => Promise<unknown>;
  routers: RouteLocationRaw;
}>();

type Isuccessstatus = EMstatus[];

const successstatus = ref<Isuccessstatus>([
  "finish",
  "wait",
  "wait",
  "wait",
  "wait",
]);

const usershow = computed({
  get() {
    return !ruleForm.usershow;
  },
  set(v) {
    ruleForm.usershow = !v;
  },
});

const isshow = computed({
  get() {
    return !ruleForm.isshow;
  },
  set(v) {
    ruleForm.isshow = !v;
  },
});

/**
 * 跳转
 */
async function next(num: string) {
  if (num === _list.value[0]?.title) {
    active.value = _list.value[0].title;
    successstatus.value = ["finish", "wait", "wait", "wait", "wait"];
  } else {
    rule.value?.validateField(["name"], async (a: any) => {
      if (a) {
        const _num = _list.value.findIndex((e) => e.title === num);
        active.value = _list.value[_num].title;
        if (_num === 1) {
          successstatus.value = ["success", "finish", "wait", "wait", "wait"];
        }
        if (_num === 2) {
          successstatus.value = [
            "success",
            "success",
            "finish",
            "wait",
            "wait",
          ];
        }
        if (_num === 3) {
          successstatus.value = [
            "success",
            "success",
            "success",
            "finish",
            "wait",
          ];
        }
        if (_num === 4) {
          successstatus.value = [
            "success",
            "success",
            "success",
            "success",
            "finish",
          ];
        }
        if (_num === 5) {
          successstatus.value = [
            "success",
            "success",
            "success",
            "success",
            "success",
          ];
        }
      }
    });
  }
}

/**
 * 平均生成分数
 */
function settestcasesscore() {
  const question = questions.value.find(
    (e) => e.oldid === dialogVisibleindex.value
  );
  if (question) {
    const length = question?.example?.length;
    if (length) {
      const score = Math.floor(100 / length);
      const yu = 100 % length;
      question.example = question.example?.map((e, k) => {
        let n = 0;
        if (k > length - yu - 1) {
          n = n + 1;
        }
        return {
          ...e,
          score: score + n,
        };
      });
    }
  }
}

const remoteMethod1 = debounce(async (query: string | number) => {
  if (query !== "") {
    const like: any = ["ID", query];
    if (Number(query) != query) {
      like[0] = "name";
    }
    loading.value = true;
    await store.dispatch("actionteam", {
      _like: like,
      tenant_id,
    });
    loading.value = false;
  }
}, 500);

async function remoteMethod2(query: string | number) {
  if (query !== "") {
    const like: Iobj<Studycodemodel.Iuser>["_like"] = ["phonenum", query];
    if (Number(query) != query) {
      like[0] = "name";
    }
    await store.dispatch("actionusers", {
      _like: like,
      tenant_id,
    });
  }
}

watch(
  () => p.ID,
  () => {
    start();
  }
);
const filename = ref("");
const request: UploadRequestHandler = async (file) => {
  const { size } = file.file;
  if (size > 1024 * 1024 * 1024) {
    ElMessage.error("上传文件过大，最大只能上传1024MB");
    return;
  }
  const data = await updateoss([file.file]);
  ruleForm.file = data.url;
  filename.value = data.name;
  return data.url;
};

const upload = ref<UploadInstance>();

const handleExceed: UploadProps["onExceed"] = async (files) => {
  upload.value!.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  await request({ file: file } as any);
};

const request2: UploadRequestHandler = async (file) => {
  const { size } = file.file;
  if (!p.isAdmin) {
    if (size > 1024 * 1024 * 1024) {
      ElMessage.error("上传文件过大，最大只能上传1GB");
      return;
    }
  }
  ElNotification({ title: "解压", message: "开始解压", type: "info" });
  const ruleForm = questions.value.find(
    (e) => e.oldid === dialogVisibleindex.value
  );
  if (ruleForm) {
    const data = await updatezip(file.file);
    ruleForm.example = (ruleForm.example ? ruleForm.example : []).concat(data);
    ElNotification({
      title: "解压",
      message: "解压成功",
      type: "success",
    });
  }
};

function close() {
  router.go(-1);
}

const rule = ref<typeof ElForm>();
const rules = activityrules;
const ruleForm = reactive<Studycodemodel.Iactivity>(
  assign({}, Activity, {
    teamid: p.teamid,
    type: "limit",
    result: 3,
  })
);
// 类型
const enum MatchType {
  LIMIT = "limit",
  PUBLIC = "public",
  TEAM = "team",
}
const matchType = ref<MatchType | undefined>();
watch(matchType, (v) => {
  if (v) {
    ruleForm.type = v === MatchType.PUBLIC ? MatchType.PUBLIC : MatchType.LIMIT;
  }
});

const questions = ref<Studycodemodel.Imatchquestion[]>([]);
const dialogVisible = ref(false);

function addclick(v: Studycodemodel.Iquestion) {
  const { ID, label, questionlabel = [], testcases, ...e } = v;
  if (!questions.value.find((e) => e.oldid === ID)) {
    questions.value.push({
      ...e,
      example: testcases,
      oldid: ID,
      label: questionlabel.map((e) =>
        String(store.state.label?.rows.find((z) => z.ID === e.labelid)?.name)
      ),
      score: 100,
    });
  }
}

function removeclick(index: number) {
  questions.value.splice(index, 1);
}

/**
 * 当前第几页
 */
const active = ref("比赛信息配置");
const context = ref("");
const htmlcontext = ref("");
const questionbankid = ref<number | undefined>();
const contexteditor = ref();
const store = useStore(Storekey);
const selectarr = ref<Studycodemodel.Iuser[]>([]);
const startTime = ref<[Date, Date]>([new Date(), new Date()]);

watch(
  () => route.query.ID,
  (v) => {
    if (v && typeof v === "number") {
      start();
      dialogVisible.value = true;
    }
  }
);

async function downloadtip() {
  const zip = new JSZip();
  [1, 2, 3].forEach((v, i) => {
    zip.file(`${i}.in`, "1");
    zip.file(`${i}.out`, "1");
  });
  zip.file(
    "提示.txt",
    "每一个测试点文件需要相同名称的两个文件，这两个文件需要一个为.in为后缀的输入示例、一个为.out为后缀的输出示例"
  );
  zip.generateAsync({ type: "blob" }).then(
    function (blob) {
      const reader = new FileReader();
      reader.readAsDataURL(blob);
      reader.onload = function (e) {
        const a = document.createElement("a");
        a.download = "示例.zip";
        if (e.target) {
          a.href = e.target.result as string;
        } else {
          a.href = location.href;
        }
        a.click();
        a.remove();
      };
    },
    function () {
      ElMessage.error("下载失败");
    }
  );
}

const customerservice = ref<Studycodemodel.Icustomerservice[]>([]);
onMounted(async () => {
  // 初始化
  await start();
  // 是否有团队
  customerservice.value = await asyncgetcustomerservice();
});

// 开始
async function start() {
  try {
    if (Number(route.query.ID)) {
      const data = await asyncgetactivity({ ID: Number(route.query.ID) });
      if (!data.info) {
        data.info = {};
      }
      Object.assign(ruleForm, data);
    } else {
      Object.assign(ruleForm, Activity);
    }
    console.log(ruleForm.type);

    startTime.value = [
      new Date(ruleForm.activitystarttime || Date.now()),
      new Date(ruleForm.activityendtime || Date.now()),
    ];
    duration.value = !!ruleForm.duration;
    if (ruleForm.teamid) {
      await store.dispatch("actionteam", { ID: ruleForm.teamid });
    }
    context.value = ruleForm.context || "";
    htmlcontext.value = ruleForm.htmlcontext || "";
    questions.value = [];
    questionbankid.value = undefined;
    const data = ruleForm.activityuser?.map((v) =>
      v.user ? v.user : { ID: v.userid }
    ) as Studycodemodel.Iuser[];
    if (data) {
      selectarr.value = data;
    } else {
      selectarr.value = [];
    }
    if (ruleForm.ID) {
      asyncselectmatchquestion({ activityid: ruleForm.ID })
        .then(([v]) => {
          if (v) {
            questions.value = v.matchquestion || [];
          }
        })
        .catch((e: undefined) => {
          ElMessage.error(e);
        });
      asyncselectactivityuser({ activityid: ruleForm.ID })
        .then((e) => {
          users.value = e.rows.map((e) => e.user || {});
        })
        .catch(() => {});
      // 回填 新版比赛类型
      if (ruleForm.type) {
        if (ruleForm.type === "limit" && ruleForm.teamid) {
          matchType.value = MatchType.TEAM;
        } else {
          matchType.value = ruleForm.type;
        }
      }
    }
    activeName.value = "first";
  } catch (e: any) {
    ElMessage.error(e);
  }
}

function change(value: Studycodemodel.Iquestion[] = []) {
  questions.value = value;
}

const activeName = ref<"first" | "two">("first");

// 提交
async function submit(index?: string) {
  // if (index === last(_list.value)?.title) {
  //   try {
  //     await ElMessageBox.confirm("是否要自动配置题目测试点分数", "Warning", {
  //       confirmButtonText: "确定",
  //       cancelButtonText: "取消",
  //       type: "warning",
  //     })
  //     updatetestcase()
  //   } catch (e) {

  //   }
  // }
  loading.value = true;
  if (!index) {
    const context = contexteditor.value?.gethtml();
    const htmlcontext = contexteditor.value?.getcontext();
    ruleForm.context = context;
    ruleForm.htmlcontext = htmlcontext;
    ruleForm.duration = duration.value ? ruleForm.duration : 0;
    ruleForm.activitystarttime = startTime.value[0];
    ruleForm.activityendtime = startTime.value[1];
    ruleForm.signupstarttime = dayjs(ruleForm.activitystarttime)
      .subtract(30, "day")
      .toDate();
    ruleForm.signupendtime = ruleForm.activityendtime;
    await p.createdorupdateactivtiy({
      data: ruleForm,
      question: questions.value.map((v, k) => {
        return {
          ...v,
          paixu: k,
        };
      }),
      users: users.value,
      teamid: p.teamid,
    });

    router.push(p.routers);
  } else {
    next(index);
  }
  loading.value = false;
}

watch(
  () => dialogVisibleindex.value,
  (v) => {
    dialogVisible2.value = Boolean(v);
  }
);
watch(
  () => dialogVisible2.value,
  (v) => {
    if (!v) {
      dialogVisibleindex.value = 0;
    }
  }
);

function adduser(t: Studycodemodel.Iuser) {
  const n = users.value.find((e) => e.ID === t.ID);
  if (!n) {
    users.value.push(t);
  }
}

async function changeteamid(i?: number) {
  if (i) {
    const data = await asyncselectteamuser({
      teamid: i,
    });
    data.rows.forEach((e) => {
      if (e.user) {
        adduser(e.user);
      }
    });
  }
}

async function _adduser(e?: number) {
  if (e) {
    const f = getuser.value?.find((t) => t.ID === e);
    if (f) {
      adduser(f);
    }
  }
}
</script>

<style scoped>
.demo-ruleForm {
  margin-top: 24px;
}

.el-upload-list__item-thumbnail {
  background-repeat: no-repeat;
  background-size: 100% 100%;
  text-align: center;
  line-height: 180px;
  color: rgba(0, 0, 0, 0);
}

.el-upload-list__item-thumbnail:hover div {
  color: #fff;
  background-color: rgba(31, 31, 31, 0.8);
}
</style>

<style>
.upload .el-upload-dragger {
  width: 300px !important;
  height: 180px !important;
}

.created-activity .el-form-item__content {
  display: block;
}
</style>
<style>
.created-activity .el-upload-list,
.created-activity .el-upload-list__item {
  margin: 0 !important;
}

/* .created-activity .el-upload-list {
  display: inline-flex;
}

.created-activity .el-upload-list::before {
  content: "文件地址:";
  color: rgba(0, 0, 0, .5) !important;
  width: 70px;
} */
</style>
